<template>
    <div class="user-management-container">
        <div class="search-container">
            <el-input v-model="searchQuery" placeholder="请输入搜索内容" class="search-input" clearable />
            <el-button type="primary" @click="handleSearch">
                <el-icon>
                    <Search />
                </el-icon>
                搜索
            </el-button>
        </div>

        <el-table :data="userList" style="width: 100%" border v-loading="loading">
            <el-table-column label="头像" width="100">
                <template #default="scope">
                    <el-avatar :size="50" :src="scope.row.userImg" />
                </template>
            </el-table-column>
            <el-table-column prop="userName" label="姓名" width="120" />
            <el-table-column prop="password" label="密码" width="120">
                <template #default="scope">
                    <span>******</span>
                    <el-button type="primary" size="small" link @click="showPassword(scope.row)">
                        查看
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column prop="age" label="年龄" width="80" />
            <el-table-column prop="gender" label="性别" width="80">
                <template #default="scope">
                    <el-tag :type="scope.row.gender === '男' ? 'primary' : 'danger'">
                        {{ scope.row.gender }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="150" />
            <el-table-column prop="email" label="邮箱" min-width="180" />
            <el-table-column label="状态" width="100">
                <template #default="scope">
                    <div class="status-display">
                        <el-switch 
                        v-model="scope.row.status" 
                        :active-value="0" 
                        :inactive-value="1"
                        @change="(val: number) => handleStatusChange(val,scope.row)" 
                        class="status-switch" 
                        />
                        <span class="status-text">
                            {{ scope.row.status === 0 ? '启用' : '禁用' }}
                        </span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <div class="operation-buttons">
                        <el-button class="edit-button" @click="handleEdit(scope.row)">
                            编辑
                        </el-button>
                        <el-button class="delete-button" @click="handleDelete(scope.row)">
                            删除
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
    <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
        @on-close="onClose" @on-confirm="commit">
        <el-form :model="keyword" ref="userFormRef" label-width="80px" :rules="rules">
            <el-form-item label="姓名" prop="userName">
                <el-input v-model="keyword.userName" placeholder="请输入姓名" disabled></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="keyword.password" placeholder="请输入密码" type="password" show-password></el-input>
            </el-form-item>
            <el-form-item label="年龄" prop="age">
                <el-input-number v-model="keyword.age" :min="1" :max="120"></el-input-number>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="keyword.gender">
                    <el-radio label="男">男</el-radio>
                    <el-radio label="女">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="keyword.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="keyword.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
        </el-form>
    </Dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Edit, Delete } from "@element-plus/icons-vue";
import { StatusType } from "@/api/login/userTable";
import type { userTable } from "@/api/login/userTable";
import { getUserListPageApi, deleteUserApi, updateUserStatusApi, updateUserApi } from "@/api/login";
import Dialog from "@/components/dialog/Dialog.vue";
import useDialog from "@/hooks/usedialog";

//弹框参数
const { dialog, onClose, onConfirm, onShow } = useDialog()

const loading = ref(false);
const userList = ref<userTable[]>([]);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取用户列表数据，使用后端分页
const fetchUserList = async () => {
    loading.value = true;
    try {
        const res = await getUserListPageApi(
            currentPage.value,
            pageSize.value,
            searchQuery.value
        );
        if (res && res.code === 200) {
            userList.value = res.data.list;
            total.value = res.data.total;
        } else {
            ElMessage.error('获取用户列表失败');
        }
    } catch (error) {
        console.error("获取用户列表失败:", error);
        ElMessage.error('获取用户列表失败');
    } finally {
        loading.value = false;
    }
};

// 搜索处理函数
const handleSearch = () => {
    currentPage.value = 1; // 重置到第一页
    fetchUserList();
};

// 分页处理函数
const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
    fetchUserList();
};

const handleCurrentChange = (page: number) => {
    currentPage.value = page;
    fetchUserList();
};

// 操作按钮处理函数
//编辑按钮
//定义编辑按钮参数
const keyword = ref<userTable>({} as userTable);
const userFormRef = ref();
// 表单验证规则
const rules = {
    userName: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
};

const handleEdit = (user: userTable) => {
    dialog.title = '编辑用户';
    onShow();
    keyword.value = { ...user }; // 使用解构赋值创建一个新对象，避免直接修改原始数据
};

const commit = () => {
    userFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // 这里可以调用更新用户的API
            const res = await updateUserApi(keyword.value)
            if(res.code == 200){
                ElMessage.success(res.msg)
                onClose();
            fetchUserList(); // 重新加载列表
            }
        } else {
            ElMessage.error('请完善表单信息');
            return false;
        }
    });
};

//删除
const handleDelete = (user: userTable) => {
    ElMessageBox.confirm(`确定要删除用户 ${user.userName} 吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    }).then(async () => {
        try {
            const res = await deleteUserApi(user.userId);
            if (res && res.code === 200) {
                ElMessage({
                    type: "success",
                    message: `用户 ${user.userName} 已删除`
                });
                fetchUserList(); // 重新加载数据
            } else {
                ElMessage.error('删除用户失败');
            }
        } catch (error) {
            console.error("删除用户失败:", error);
            ElMessage.error('删除用户失败');
        }
    }).catch(() => {
        // 取消删除
    });
};
//更改用户状态
// 状态切换回调方法
const handleStatusChange = async (val: number, row: any) => {
    try {
        const res = await updateUserStatusApi(row);
        if (res.code === 200) {
            ElMessage.success(res.msg);
            fetchUserList();
        } else if (res.code === 500) {
            // 显示错误信息
            ElMessage.error(res.msg || '状态更新失败');
            
            // 记录错误日志
            console.error('用户状态更新失败:', res);
            
            // 延迟恢复开关状态，提供视觉反馈
            setTimeout(() => {
                row.status = row.status === 1 ? 0 : 1;
            }, 500); // 延迟500毫秒
            
            // 可以在这里添加其他处理逻辑，如尝试重新获取用户信息
        }
    } catch (error) {
        // 处理API调用异常
        console.error('状态更新出现异常:', error);
        ElMessage.error('系统异常，请稍后再试');
        
        // 延迟恢复开关状态
        setTimeout(() => {
            row.status = row.status === 1 ? 0 : 1; // 恢复状态
        }, 500); // 延迟500毫秒
    }
};

//查看密码信息提示
const showPassword = (user: userTable) => {
    ElMessageBox.alert(user.password, "密码信息", {
        confirmButtonText: "确定"
    });
};

onMounted(() => {
    fetchUserList();
});
</script>

<style scoped>
.user-management-container {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
    margin-right: 10px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.operation-buttons {
    display: flex;
    gap: 10px;
    padding: 5px 0;
}

.edit-button {
    background-color: #409EFF;
    color: white;
    border: none;
    height: 28px;
    padding: 0 15px;
    border-radius: 4px;
}

.delete-button {
    background-color: #F56C6C;
    color: white;
    border: none;
    height: 28px;
    padding: 0 15px;
    border-radius: 4px;
}

.status-display {
    display: flex;
    align-items: center;
    gap: 5px;
}

.status-text {
    font-size: 14px;
    color: #606266;
}
</style>